//
//  IntersectionDetailPage.m
//  Portable Traffic Signal Assistor
//
//  Created by Ding on 9/1/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "IntersectionDetailPage.h"

@interface IntersectionDetailPage ()

@end

@implementation IntersectionDetailPage
@synthesize sections=_sections;
@synthesize nameSection=_nameSection;
@synthesize coordinateSection=_coordinateSection;
@synthesize timingPatternListSection=_timingPatternListSection;
@synthesize intersectionNameTextView=_intersectionNameTextView;
@synthesize latitudeTextView=_latitudeTextView;
@synthesize longitudeTextView=_longitudeTextView;
@synthesize subSystem=_subSystem;
@synthesize agency=_agency;
@synthesize intersection=_intersection;
@synthesize timingPatternList=_timingPatternList;
@synthesize linkListSection=_linkListSection;
@synthesize linkList=_linkList;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id) initWithNibNameAndIntersection:(NSString *)nibName agency:(Agency *)agency subSystem:(SubSystem *)subSystem intersection:(Intersection *) intersection bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    if (self) {
        self.agency=agency;
        self.subSystem=subSystem;
        self.intersection=intersection;
        self.timingPatternList=[XMLParser getTimingPatternList:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    }
    return self;
}

- (void) dealloc
{
    [_sections release];
    [_nameSection release];
    [_coordinateSection release];
    [_timingPatternListSection release];
    [_intersectionNameTextView release];
    [_latitudeTextView release];
    [_longitudeTextView release];
    [_subSystem release];
    [_agency release];
    [_intersection release];
    [_timingPatternList release];
    [_linkListSection release];
    [_linkList release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    
    if(!_nameSection)
    {
        _nameSection=[[TableSection alloc]init];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _nameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_nameSection.contents addObject:self.intersection.intersectionName];
        
        _nameSection.header=@"Intersection Name";
    }
    if(!_coordinateSection)
    {
        _coordinateSection=[[TableSection alloc]init];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _coordinateSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_coordinateSection.contents addObject:[NSString stringWithFormat:@"%f",self.intersection.intersectionCoordinate.latitude]];
        [_coordinateSection.contents addObject:[NSString stringWithFormat:@"%f",self.intersection.intersectionCoordinate.longitude]];
        
        _coordinateSection.header=@"Intersection Coordinate";
    }
    if(!_timingPatternListSection)
    {
        _timingPatternListSection=[[TableSection alloc]init];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _timingPatternListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.timingPatternList.count; i++) {
            TimingPattern *timingPattern=[self.timingPatternList objectAtIndex:i];
            [_timingPatternListSection.contents addObject:timingPattern.timingPatternName];
        }
        
        
        _timingPatternListSection.header=@"Timing Pattern List";
    }
    if (!_linkListSection) {
        _linkListSection=[[TableSection alloc] init];
        _linkListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        self.linkList=[[[NSMutableArray alloc] init] autorelease];
        NSArray *linkListFromIntersection=[XMLParser getLinkListFromIntersection:self.agency.agencyID subSystemID:self.subSystem.subSystemID intersectionID:self.intersection.intersectionID];
        NSArray *linkListToIntersection=[XMLParser getLinkListToIntersection:self.agency.agencyID subSystemID:self.subSystem.subSystemID intersectionID:self.intersection.intersectionID];
        [self.linkList addObjectsFromArray:linkListFromIntersection];
        [self.linkList addObjectsFromArray:linkListToIntersection];
        for (int i=0; i<self.linkList.count; i++) {
            Link *link1=[self.linkList objectAtIndex:i];
            for (int j=i; j<self.linkList.count; j++) {
                Link *link2=[self.linkList objectAtIndex:j];
                if ([link1.linkID isEqualToString:link2.linkID]) {
                    [self.linkList removeObjectAtIndex:j];
                    j=j-1;
                }
            }
        }
        for (int i=0; i<self.linkList.count; i++) {
            Link *link=[self.linkList objectAtIndex:i];
            NSString *direction=link.linkDirection;
            NSString *content=@"";
            if ([direction isEqualToString:@"Two Way"]) {
                direction=@"<=>";
                if ([link.fromIntersectionID isEqualToString:self.intersection.intersectionID]) {
                    Intersection* otherIntersection=[[XMLParser getIntersection:link.toIntersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID] retain];
                    content=[NSString stringWithFormat:@"%@\n%@%@",link.linkName,direction,otherIntersection.intersectionName];
                    [otherIntersection release];
                }else if ([link.toIntersectionID isEqualToString:self.intersection.intersectionID])
                {
                    Intersection* otherIntersection=[[XMLParser getIntersection:link.fromIntersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID] retain];
                    content=[NSString stringWithFormat:@"%@\n%@%@",link.linkName,direction,otherIntersection.intersectionName];
                    [otherIntersection release];
                }
                
                
                
            }else
            {
                if ([link.fromIntersectionID isEqualToString:self.intersection.intersectionID]) {
                    direction=@"->";
                    Intersection* otherIntersection=[[XMLParser getIntersection:link.toIntersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID] retain];
                    content=[NSString stringWithFormat:@"%@\n%@%@",link.linkName,direction,otherIntersection.intersectionName];
                    [otherIntersection release];
                }else if ([link.toIntersectionID isEqualToString:self.intersection.intersectionID])
                {
                    direction=@"<-";
                    Intersection* otherIntersection=[[XMLParser getIntersection:link.fromIntersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID] retain];
                    content=[NSString stringWithFormat:@"%@\n%@%@",link.linkName,direction,otherIntersection.intersectionName];
                    [otherIntersection release];
                }
            }
            
            [_linkListSection.contents addObject:content];
        }
        _linkListSection.header=@"Connected Link List";
    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        [_sections addObject:self.nameSection];
        [_sections addObject:self.coordinateSection];
        [_sections addObject:self.timingPatternListSection];
        [_sections addObject:self.linkListSection];
    }
    
    UITapGestureRecognizer *gestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewReturn:)] autorelease];
    gestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:gestureRecognizer];
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,nil ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.sections=nil;
    self.nameSection=nil;
    self.coordinateSection=nil;
    self.timingPatternListSection=nil;
    self.intersectionNameTextView=nil;
    self.latitudeTextView=nil;
    self.longitudeTextView=nil;
    self.subSystem=nil;
    self.agency=nil;
    self.intersection=nil;
    self.timingPatternList=nil;
    self.linkListSection=nil;
    self.linkList=nil;
}
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self updateView];
}

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell* cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;
    cell.textLabel.text=sectionContentString;
    
    switch (indexPath.section) {
        case 0:
        {
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
//            CGFloat height=[TableSection calculateStringHeight:[[section contents] objectAtIndex:indexPath.row]];
            CGFloat height=cell.frame.size.height;
            self.intersectionNameTextView=[[[UITextView alloc] initWithFrame:CGRectMake(1, 5, (CONST_portraitCellWidth-2), (height-10))] autorelease];
            [self.intersectionNameTextView setText:sectionContentString];
            [self.intersectionNameTextView setFont:[TableSection TitleFont]];
            //            [self.projectNameTextView setTag:ProjectNameTextView];
            self.intersectionNameTextView.delegate=self;
            
            [[cell contentView] addSubview:self.intersectionNameTextView];
            [cell setBackgroundColor:[TableSection WhiteColor]];
            
            return cell;
        }
            
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    cell.selectionStyle=UITableViewCellSelectionStyleNone;
                    
                    CGFloat height=[TableSection calculateStringHeight:[[section contents] objectAtIndex:indexPath.row]];
                    self.latitudeTextView=[[[UITextView alloc] initWithFrame:CGRectMake(1, 5, (CONST_portraitCellWidth-2), (height-10))] autorelease];
                    [self.latitudeTextView setText:sectionContentString];
                    [self.latitudeTextView setFont:[TableSection TitleFont]];
                    //            [self.projectNameTextView setTag:ProjectNameTextView];
                    self.latitudeTextView.delegate=self;
                    
                    [[cell contentView] addSubview:self.latitudeTextView];
                    [cell setBackgroundColor:[TableSection WhiteColor]];
                    
                    return cell;
                }
                    break;
                case 1:
                {
                    cell.selectionStyle=UITableViewCellSelectionStyleNone;
                    
                    CGFloat height=[TableSection calculateStringHeight:[[section contents] objectAtIndex:indexPath.row]];
                    self.longitudeTextView=[[[UITextView alloc] initWithFrame:CGRectMake(1, 5, (CONST_portraitCellWidth-2), (height-10))] autorelease];
                    [self.longitudeTextView setText:sectionContentString];
                    [self.longitudeTextView setFont:[TableSection TitleFont]];
                    //            [self.projectNameTextView setTag:ProjectNameTextView];
                    self.longitudeTextView.delegate=self;
                    
                    [[cell contentView] addSubview:self.longitudeTextView];
                    [cell setBackgroundColor:[TableSection WhiteColor]];
                    
                    return cell;
                }
                    break;
                    
                default:
                    break;
            }
            
        }
            break;
        case 3:
        {
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        }
            break;
            
        default:
            cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
            break;
    }
    
    
    
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
    UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
    aLabel.text =[[self.sections objectAtIndex:section] header] ;
    aLabel.font = [UIFont boldSystemFontOfSize:16.0];
    aLabel.textAlignment = UITextAlignmentLeft;
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.textColor=[UIColor darkGrayColor];
    
    
    [headerView addSubview:aLabel];
    switch (section) {
        case 0:
        {
            return headerView;
        }
            break;
        case 1:
        {
            UIButton *mapButton=[UIButton buttonWithType:UIButtonTypeCustom];
            [mapButton setFrame:CGRectMake(320-40, 0.0f, 30.0f, 30.0f)];
            [mapButton addTarget:self action:@selector(clickMapButton:) forControlEvents:UIControlEventTouchUpInside];
            //    [self.button setImage:[UIImage imageNamed:@"GPS.png"] forState:UIControlStateNormal];
            [mapButton setImage:[UIImage imageNamed:@"location_on_map.png"] forState:UIControlStateNormal];
            [headerView addSubview:mapButton];
            return headerView;
        }
            break;
        case 3:
        {
            //Then you can add a UILabel to your headerView
            UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
            [newbutton setFrame:CGRectMake(180,4,30,30)];
            //    [newbutton setTitle:@"Remove" forState:UIControlStateNormal];
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
            [newbutton setTag:(section)];
            [newbutton addTarget:self action:@selector(clickAddIntersectionButton:)
                forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:newbutton];
        }
            break;
            
        default:
        {
            //Then you can add a UILabel to your headerView
//            UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
//            [newbutton setFrame:CGRectMake(160,4,30,30)];
//            //    [newbutton setTitle:@"Remove" forState:UIControlStateNormal];
//            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
//            [newbutton setTag:(section)];
//            [newbutton addTarget:self action:@selector(clickAddSubSystemButton:)
//                forControlEvents:UIControlEventTouchUpInside];
//            [headerView addSubview:newbutton];
        }
            break;
    }
    
    
    
    
    return headerView;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==3) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // Commit the delete
        [XMLParser removeLink:[[self.linkList objectAtIndex:indexPath.row] linkID] agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        [self updateView];
        
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    
    return [[self.sections objectAtIndex:section] header];
    
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    
    switch (indexPath.section) {
        
        case 2:
        {
            NSArray* signalList=[XMLParser getSignalList:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:[[self.timingPatternList objectAtIndex:indexPath.row] timingPatternID]];
            int index=-1;
            for (int i=0; i<signalList.count; i++) {
                if ([self.intersection.intersectionID isEqualToString:[[signalList objectAtIndex:i] signalID]]) {
                    index=i;
                    break;
                }
            }
            if (index==-1) {
                return;
            }
            SignalDetailViewController *detailViewController=[[[SignalDetailViewController alloc] initWithNibNameAndSignal:@"SignalDetailViewController" agency:self.agency subSystem:self.subSystem timingPattern:[self.timingPatternList objectAtIndex:indexPath.row] signalList:signalList signalIndex:index automaticPlayOrNot:NO  bundle:nil] autorelease];
            [detailViewController setTitle:@"Signal Detail"];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            break;
        case 3:
        {
            LinkDetailPage *linkDetailPage=[[[LinkDetailPage alloc] initWithNibName:@"LinkDetailPage" bundle:nil link:[self.linkList objectAtIndex:indexPath.row] agency:self.agency subSystem:self.subSystem] autorelease];
            [linkDetailPage setTitle:@"Link Detail"];
            [self.navigationController pushViewController:linkDetailPage animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            break;
            
        default:
            break;
    }
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        
        case 2:
        {
            NSArray* signalList=[XMLParser getSignalList:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:[[self.timingPatternList objectAtIndex:indexPath.row] timingPatternID]];
            int index=-1;
            for (int i=0; i<signalList.count; i++) {
                if ([self.intersection.intersectionID isEqualToString:[[signalList objectAtIndex:i] signalID]]) {
                    index=i;
                    break;
                }
            }
            if (index==-1) {
                return;
            }
            
            SignalAssistorDetailEditViewController *detailViewController=[[[SignalAssistorDetailEditViewController alloc] initWithNibNameAndSignal:@"SignalAssistorDetailEditViewController" agency:self.agency subSystem:self.subSystem timingPattern:[self.timingPatternList objectAtIndex:indexPath.row] signal:[signalList objectAtIndex:index] bundle:nil] autorelease];
            [detailViewController setTitle:@"Edit Signal"];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            
        default:
            break;
    }
}

#pragma mark -TextView Delegate
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    self.intersection.intersectionName=self.intersectionNameTextView.text;
    CLLocationCoordinate2D coordinate={[self.latitudeTextView.text floatValue],[self.longitudeTextView.text floatValue]};
    self.intersection.intersectionCoordinate=coordinate;
    [XMLParser updateIntersection:self.intersection agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    for (TimingPattern *timingPattern in self.timingPatternList) {
        Signal *signal=[XMLParser getSignal:self.intersection.intersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:timingPattern.timingPatternID];
        signal.signalName=self.intersection.intersectionName;
        [XMLParser updateSignal:signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:timingPattern.timingPatternID];
    }
    
    
    if(self.nameSection)
    {
        
        self.nameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [self.nameSection.contents addObject:self.intersection.intersectionName];
        
        self.nameSection.header=@"Intersection Name";
    }
    if(self.coordinateSection)
    {
        self.coordinateSection=[[[TableSection alloc]init] autorelease];
        
        
        [self.coordinateSection.contents addObject:[NSString stringWithFormat:@"%f",self.intersection.intersectionCoordinate.latitude]];
        [self.coordinateSection.contents addObject:[NSString stringWithFormat:@"%f",self.intersection.intersectionCoordinate.longitude]];
        
        self.nameSection.header=@"Intersection Coordinate";
    }
    return YES;
}

#pragma mark -customized functions
- (IBAction)textViewReturn:(id)sender
{
    [self.intersectionNameTextView resignFirstResponder];
    [self.latitudeTextView resignFirstResponder];
    [self.longitudeTextView resignFirstResponder];
}
- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void) updateView
{
    self.intersection=[XMLParser getIntersection:self.intersection.intersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    if(self.nameSection)
    {
        self.nameSection=[[[TableSection alloc]init] autorelease];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _nameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_nameSection.contents addObject:self.intersection.intersectionName];
        
        _nameSection.header=@"Intersection Name";
    }
    if(self.coordinateSection)
    {
        self.coordinateSection=[[[TableSection alloc]init] autorelease];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _coordinateSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_coordinateSection.contents addObject:[NSString stringWithFormat:@"%f",self.intersection.intersectionCoordinate.latitude]];
        [_coordinateSection.contents addObject:[NSString stringWithFormat:@"%f",self.intersection.intersectionCoordinate.longitude]];
        
        _coordinateSection.header=@"Intersection Coordinate";
    }
    if(self.timingPatternListSection)
    {
        self.timingPatternListSection=[[[TableSection alloc]init] autorelease];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _timingPatternListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.timingPatternList.count; i++) {
            TimingPattern *timingPattern=[self.timingPatternList objectAtIndex:i];
            [_timingPatternListSection.contents addObject:timingPattern.timingPatternName];
        }
        
        
        _timingPatternListSection.header=@"Timing Pattern List";
    }
    if (self.linkListSection) {
        self.linkList=[[[NSMutableArray alloc] init] autorelease];
        self.linkListSection=[[[TableSection alloc] init] autorelease];
        _linkListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        self.linkList=[[[NSMutableArray alloc] init] autorelease];
        NSArray *linkListFromIntersection=[XMLParser getLinkListFromIntersection:self.agency.agencyID subSystemID:self.subSystem.subSystemID intersectionID:self.intersection.intersectionID];
        NSArray *linkListToIntersection=[XMLParser getLinkListToIntersection:self.agency.agencyID subSystemID:self.subSystem.subSystemID intersectionID:self.intersection.intersectionID];
        [self.linkList addObjectsFromArray:linkListFromIntersection];
        [self.linkList addObjectsFromArray:linkListToIntersection];
        for (int i=0; i<self.linkList.count; i++) {
            Link *link1=[self.linkList objectAtIndex:i];
            for (int j=i+1; j<self.linkList.count; j++) {
                Link *link2=[self.linkList objectAtIndex:j];
                if ([link1.linkID isEqualToString:link2.linkID]) {
                    [self.linkList removeObjectAtIndex:j];
                    j=j-1;
                }
            }
        }
        for (int i=0; i<self.linkList.count; i++) {
            Link *link=[self.linkList objectAtIndex:i];
            NSString *direction=link.linkDirection;
            NSString *content=@"";
            if ([direction isEqualToString:@"Two Way"]) {
                direction=@"<=>";
                if ([link.fromIntersectionID isEqualToString:self.intersection.intersectionID]) {
                    Intersection* otherIntersection=[[XMLParser getIntersection:link.toIntersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID] retain];
                    content=[NSString stringWithFormat:@"%@\n%@%@",link.linkName,direction,otherIntersection.intersectionName];
                    [otherIntersection release];
                }else if ([link.toIntersectionID isEqualToString:self.intersection.intersectionID])
                {
                    Intersection* otherIntersection=[[XMLParser getIntersection:link.fromIntersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID] retain];
                    content=[NSString stringWithFormat:@"%@\n%@%@",link.linkName,direction,otherIntersection.intersectionName];
                    [otherIntersection release];
                }
                
                
                
            }else
            {
                if ([link.fromIntersectionID isEqualToString:self.intersection.intersectionID]) {
                    direction=@"->";
                    Intersection* otherIntersection=[[XMLParser getIntersection:link.toIntersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID] retain];
                    content=[NSString stringWithFormat:@"%@\n%@%@",link.linkName,direction,otherIntersection.intersectionName];
                    [otherIntersection release];
                    
                }else if ([link.toIntersectionID isEqualToString:self.intersection.intersectionID])
                {
                    direction=@"<-";
                    Intersection* otherIntersection=[[XMLParser getIntersection:link.fromIntersectionID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID] retain];
                    content=[NSString stringWithFormat:@"%@\n%@%@",link.linkName,direction,otherIntersection.intersectionName];
                    [otherIntersection release];
                }
            }
            
            [_linkListSection.contents addObject:content];
        }
        _linkListSection.header=@"Connected Link List";
    }
    if (self.sections) {
        self.sections = [[[NSMutableArray alloc] init] autorelease];
        [_sections addObject:self.nameSection];
        [_sections addObject:self.coordinateSection];
        [_sections addObject:self.timingPatternListSection];
        [_sections addObject:self.linkListSection];
    }
    [self.tableView reloadData];
}


- (IBAction)clickMapButton:(id)sender {
    IntersectionLocationEditMapViewController *detailViewController=[[[IntersectionLocationEditMapViewController alloc] initWithNibNameAndSignal:@"IntersectionLocationEditMapViewController" intersection:self.intersection agency:self.agency subSystem:self.subSystem bundle:nil] autorelease];
    //    self.navigationItem.titleView=nil;
    //    [self.imageView removeFromSuperview];
    //    self.navigationItem.title=@"Home";
    [detailViewController setTitle:self.intersection.intersectionName];
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (void) clickAddIntersectionButton:(id)sender
{
    Link *link=[[[Link alloc] init] autorelease];
    [link setLinkID:[XMLParser createLinkID:self.agency.agencyID subSystemID:self.subSystem.subSystemID]];
    [link setLinkName:@"New Link"];
    [link setSpeedLimit:@"40"];
    [link setLinkDirection:@"One Way"];
    [link setLength:@"100"];
    [link setFromIntersectionID:self.intersection.intersectionID];
    [link setToIntersectionID:self.intersection.intersectionID];
    [XMLParser createLink:link agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];

    
    
    
    [self updateView];
}


@end
